﻿using FluentFTP;
using HAF.Dispatcher;
using HAF.Dispatcher.Enum;
using HAF.Dispatcher.Impl;
using HAF.Dispatcher.WorkItem;
using HAF.LogUtility;
using HAF.LogUtility.Assistantor;
using HAF.LogUtility.Enum;
using HAF.LogUtility.Model;
using Iptv.UploadResourceItem.Helper;
using Iptv.UploadResourceItem.Model;
using RDS.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace Iptv.UploadResourceItem
{
    /// <summary>
    /// 介质上传工作项
    /// </summary>
    public class UploadWorkItem : BaseWorkerItem, IPluginRegistable, IDisposable
    {
        const string _defLogName = "SysMonitor";
        private LoadConfig _runSiteConfig;
        private Dictionary<string, int> taskList = new Dictionary<string, int>();
        private string _distributeSrvApiUrl, _statSrvApiUrl;
        List<TaskModel> taskModels = new List<TaskModel>();

        /// <summary>
        /// 文件处理进度输出
        /// </summary>
        public Action<FtpProgress> ShowUploadProcessEvent;
        /// <summary>
        /// 任务注册
        /// </summary>
        /// <param name="id"></param>
        /// <param name="objTask"></param>
        /// <returns></returns>
        public bool Regist(string id, object objTask)
        {
            if (string.IsNullOrEmpty(id))
            {
                WriteDebugMessage(string.Format("金沙引擎：方法{0}数据解析错误：{1}", System.Reflection.MethodBase.GetCurrentMethod().Name, "参数ID为空"));
                return false;
            }
            if (objTask == null)
            {
                WriteDebugMessage(string.Format("金沙引擎：方法{0}数据解析错误：{1}", System.Reflection.MethodBase.GetCurrentMethod().Name, "参数obj为空"));
                return false;
            }

            try
            {
                var downJob = new UploadWorkItem()
                {
                    ID = int.Parse(TimeHelper.GetTimeStamp()),
                    TaskID = id,
                    Name = string.Concat("DownRes", id),
                    Priority = 10,
                    Model = EnumItemModel.Multi,
                    RedoTimes = 2,
                    WorkID = _defLogName,
                    WorkJson = JsonAssistant.Serialize(objTask),
                    AllowRemoteExec = false,
                    WriteConsoleMessageEvent = RuntimeAdapter.ShowConsol,
                    WorkItems = objTask,
                    RunLogLevel = HAF.LogUtility.Enum.EnumLogLevel.All
                };
                Dispatcher.GetInstance().RegistTaskItem(downJob);

                //RuntimeControler.Tasks.Add(id, downJob);
                WriteDebugMessage(string.Format("金沙引擎：创建{0}工作项完成，下载资源请求已加入执行队列", id));
                return true;
            }
            catch (Exception ex)
            {
                WriteDebugMessage(string.Format("金沙引擎：方法{0}发生异常：{1}", System.Reflection.MethodBase.GetCurrentMethod().Name, ex.ToString()));
                return false;
            }
        }

        /// <summary>
        /// 任务执行
        /// </summary>
        public override void ExecItem()
        {
            base.ExecItem();
            ReportMessageEvent = PushLog;
            RuntimeAdapter.Tasks.Clear();
            RefreshConfig();
            //提取请求方输入参数
            Tack actTrace = JsonAssistant.Deserialize<Tack>(WorkJson);
            RuntimeAdapter.RunRepeat = actTrace.Action.ToLower().Equals("start");
            if (RuntimeAdapter.RunRepeat)
            {
                ShowDebugMessage("上传任务循环模式启动！");
                Thread uploadMonitor = new Thread(delegate () { CreateTaskMonitor(_runSiteConfig); }) { Name = "TaskMonitor", IsBackground = true, Priority = ThreadPriority.Highest };
                uploadMonitor.Start();
            }
            else
            {
                ShowWarnMessage("上传任务循环模式将被停止");
                this.Statu = EnumRunItemStatu.End;
            }
        }

        private void RefreshConfig()
        {
            //获取本地配置文件 每次执行的时候读取，实现热配置
            string loadConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, RuntimeAdapter.PluginDir, "UpLoadConfig.json");
            ShowDebugMessage("获取本地配置文件{0}", loadConfigPath);
            _runSiteConfig = JsonAssistant.FromFile<LoadConfig>(loadConfigPath);
        }

        private void CreateTaskMonitor(LoadConfig loadConfig)
        {
            taskList.Clear();
            taskModels.Clear();
            string mothod = loadConfig.TaskDistributeType;
            _distributeSrvApiUrl = loadConfig.TaskDistributeHost.Replace("{srvTag}", loadConfig.DistributeSrvTag);
            _statSrvApiUrl = loadConfig.TaskReport;
            while (RuntimeAdapter.RunRepeat)
            {
                int iWaitTask = 0;
                try
                {
                    foreach (var item in taskList)
                    {
                        //值为 0表示待执行 1表示执行中 2表示执行完成 -1 表示执行失败需重试的，重试满了还是不行直接为2
                        //查找所有待执行任务，并进行计数
                        if (item.Value == 1) iWaitTask++;
                    }
                    if (iWaitTask > _runSiteConfig.MaxTaskCount)
                    {
                        ShowDebugMessage("上传任务执行数量已达到最大值 {0}", _runSiteConfig.MaxTaskCount);
                        Thread.Sleep(1 * 60 * 1000); //暂停一分钟
                        RefreshConfig();
                        continue;
                    }

                    ShowDebugMessage("获取新的上传任务");
                    string localFile = string.Empty;
                    var taskinfo = GetRemoteTask(_distributeSrvApiUrl);
                    if (taskinfo != null)
                    {
                        ShowDebugMessageExt(taskinfo.Id, "添加任务[{0}]到前端展示", taskinfo.Id, taskinfo.FileName);
                        if (RuntimeAdapter.Tasks.Exists(t=> t.ID == taskinfo.Id))
                        {
                            UpdateTopTaskState(taskinfo.Id, 1);
                        }
                        else
                        {
                            RuntimeAdapter.Tasks.Add(new RunTask()
                            {
                                ID = taskinfo.Id,
                                Type = "Upload",
                                Comment = taskinfo.FileName,
                                CreateTime = DateTime.Now,
                                EndTime = DateTime.MaxValue,
                                Tag = taskinfo.Id,
                                Name = taskinfo.OutName,
                                State = 1
                            });
                        }
                        
                        //重复任务处理
                        if (taskList.ContainsKey(taskinfo.Id))
                        {
                            taskList.Remove(taskinfo.Id);
                        }
                        RunUploadTask(taskinfo);
                    }
                    else
                    {
                        ShowWarnMessage("任务未正常获取或被取消");
                    }
                }
                catch (Exception ex)
                {
                    ShowErrMessage(ex.ToString());
                }

                Thread.Sleep(1 * 40 * 1000); //暂停 40秒
            }
            ShowDebugMessage("循环提取任务已失效");
        }

        private void RunUploadTask(TaskModel taskinfo)
        {
            try
            {
                taskList.Add(taskinfo.Id, 0);
                taskModels.Add(taskinfo);
                string localRealPath = taskinfo.LocalFileFullPath;
                ShowDebugMessageExt(taskinfo.Id, "当前任务媒体类型{0}", taskinfo.MediaType);
                if (taskinfo.MediaType == "Picture")
                {
                    localRealPath = GetRemoteFile(taskinfo.Id, taskinfo.LocalFileFullPath, taskinfo.RealName);
                }

                if (string.IsNullOrEmpty(localRealPath))
                {
                    UpdateRemoteTaskStat(taskinfo.Id, "停止", 0);
                    UpdateTopTaskState(taskinfo.Id, -1);
                    ShowErrMessageExt(taskinfo.Id, "任务[{0}] {1}未成功获取到本地媒体文件", taskinfo.Id, taskinfo.FileName);
                }
                else
                {
                    
                     
                    ShowDebugMessageExt(taskinfo.Id, "当前任务将采用[{0}]模式上传", taskinfo.OutType.ToUpper());
                    if (taskinfo.OutType.ToLower().Equals("fold"))
                    {
                        //启动新的线程进行下载
                        Task.Run(delegate () { CopyTaskRun(taskinfo.Id, taskinfo.RemoteFileFullPath, localRealPath); });
                    }
                    else if (taskinfo.OutType.ToLower().Equals("ftp"))
                    {
                        //启动新的线程进行下载
                        Task.Run(delegate () { UploadTaskRun(taskinfo.Id, taskinfo.RemoteFileFullPath, localRealPath); });
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrMessageExt(taskinfo.Id, ex.ToString());
                UpdateRemoteTaskStat(taskinfo.Id, "停止", 0);
                UpdateTopTaskState(taskinfo.Id, -1);
            }
            
        }

        /// <summary>
        /// 主动获取任务
        /// </summary>
        /// <param name="hostUrl">MRS-API接口地址</param>
        /// <returns></returns>
        private TaskModel GetRemoteTask(string hostUrl)
        {
            /* 
             * {"ReturnValue":
             * {"Id":"ce43b14d-077f-4d06-9e0f-b23c2cdffae6",
             * "FileName":"我的萌宠恋人第07集.ts",
             * "SourcePath":"\\\\sctv.x410\\Media03\\Media",
             * "SourceRelativePath":"Multiset\\202407\\04\\1bf235b7-6b52-4348-9014-b1a322e511d5.ts", "202412\04\4661a7ac-10a5-4b85-8ecb-a2a052d62738.jpg"
             * "TargetRelativePath":"202412\\05\\1bf235b7-6b52-4348-9014-b1a322e511d5.ts",
             * "OutCode":"LTICMS06","OutName":"移动底量（新）",
             * "OutType":"ftp",
             * "OutPath":"ftp://mrsmobile:mobileJxm2024panda@172.25.8.181:21/"
             * },
             * "Flag":true,"ErrorMessage":"","ErrorCode":"","StarckMessage":""}
             */
            TaskModel taskData = null;
            ShowInfoMessage("到{0}获取上传任务", hostUrl);
            string responseStr = WebHelper.GetHttpResponse(hostUrl, "GET", "application/json", string.Empty);
            if (!string.IsNullOrEmpty(responseStr))
            {
                ShowDebugMessage("获取远端任务信息：/r/n {0}", responseStr);
                //解析任务信息
                DistributeMessage injectMsg = JsonAssistant.Deserialize<DistributeMessage>(responseStr);
                if (injectMsg != null && injectMsg.ReturnValue != null)
                {
                    taskData = injectMsg.ReturnValue;
                    ShowInfoMessageExt(taskData.Id, "上传[{0}]任务开始执行", taskData.FileName);
                    //获取源文件扩展名
                    string fileEx = Path.GetExtension(taskData.SourceRelativePath);
                    taskData.RealName = Path.GetFileName(taskData.SourceRelativePath);
                    ShowDebugMessageExt(taskData.Id, "本地源文件{0}的后缀名为{1}", taskData.SourceRelativePath, fileEx);
                    //图片文件判定
                    if (fileEx.ShowMediaType() == "Picture")
                    {
                        //图片文件必须先到Web管理平台下载后才能上传
                        ShowDebugMessageExt(taskData.Id, "当前源文件{0}被判定为图片[Picture]", taskData.RealName);
                        taskData.MediaType = "Picture";
                        taskData.LocalFileFullPath = string.Concat(_runSiteConfig.PictureUrlPrefix, taskData.SourceRelativePath.Replace("\\","/"));
                    }
                    else
                    {
                        ShowDebugMessageExt(taskData.Id, "当前源文件{0}被判定为视频[Movie]", taskData.RealName);
                        taskData.MediaType = "Movie";
                        //本地文件全路径
                        taskData.LocalFileFullPath = Path.Combine(taskData.SourcePath, taskData.SourceRelativePath);
                    } 
                   
                    bool isSkip = false;
                    ShowDebugMessageExt(taskData.Id, "任务{0}是否跳过执行判断", taskData.FileName);
                    //是否跳过判断
                    if (_runSiteConfig.SkipNodeTag != null && _runSiteConfig.SkipNodeTag.Length > 0)
                    {
                        foreach (var item in _runSiteConfig.SkipNodeTag)
                        {
                            isSkip = taskData.OutCode.ToLower().Equals(item.ToLower());
                            if (isSkip) break;
                        }
                    }
                    if (isSkip)
                    {
                        ShowWarnMessageExt(taskData.Id, "注入标记[{0}]任务被跳过", taskData.OutCode);
                        UpdateRemoteTaskStat(taskData, "停止");
                        return null;
                    }
                    //文件分发模式判断 文件夹拷贝模式
                    if (taskData.OutType.ToLower().Equals("fold"))
                    {
                        ParseMediaPath(taskData);
                    }
                    else if (taskData.OutType.ToLower().Equals("ftp"))
                    {
                        ParseMediaUrl(taskData);
                    }
                    
                    ShowWarnMessageExt(taskData.Id, "本地文件全路径为{0} 上传文件全路径为{1}", taskData.LocalFileFullPath, taskData.RemoteFileFullPath);
                }
                else
                {
                    ShowErrMessage("获取远端任务信息解析失败");
                }

            }
            return taskData;
        }

        private void ParseMediaPath(TaskModel taskData)
        {
            ShowDebugMessageExt(taskData.Id, "注入标记[{0}]任务将采用拷贝模式上传", taskData.OutCode);
            taskData.RemoteFileFullPath = Path.Combine(taskData.OutPath.TrimEnd('/'), taskData.TargetRelativePath.Replace("/","\\"));
        }

        private void ParseMediaUrl(TaskModel taskData)
        {
            //视频文件上传随机主机模式处理
            if (taskData.MediaType == "Movie" && _runSiteConfig.RandomNodeTag != null && _runSiteConfig.RandomNodeTag.Count > 0)
            {
                var tmpNode = _runSiteConfig.RandomNodeTag.Find(t => t.Tag.ToLower().Equals(taskData.OutCode.ToLower()));
                if (tmpNode != null && tmpNode.UploadHosts != null && tmpNode.UploadHosts.Length > 0)
                {
                    ShowDebugMessageExt(taskData.Id, "注入标记[{0}]与[{1}]一致，任务将启用多HOST模式FTP上传", taskData.OutCode, tmpNode.Tag);
                    string runhost = string.Empty;
                    if (string.IsNullOrEmpty(RuntimeAdapter.HostIP))
                    {
                        runhost = tmpNode.UploadHosts[0];
                    }
                    else
                    {
                        ShowWarnMessageExt(taskData.Id, RuntimeAdapter.HostIP);
                        foreach (var item in tmpNode.UploadHosts)
                        {
                            if (!RuntimeAdapter.HostIP.Equals(item))
                            {
                                runhost = item;
                            }
                        }
                    }
                    RuntimeAdapter.HostIP = runhost;
                    taskData.RemoteFileFullPath = string.Concat(runhost, taskData.TargetRelativePath.Replace("\\", "/"));
                }
                else
                {
                    ShowDebugMessageExt(taskData.Id, "注入标记[{0}]任务将使用FTP模式直接上传", taskData.OutCode);
                    taskData.RemoteFileFullPath = string.Concat(taskData.OutPath, taskData.TargetRelativePath.Replace("\\", "/"));
                }
            }
            else
            {
                ShowDebugMessageExt(taskData.Id, "注入标记[{0}]任务将使用FTP模式直接上传", taskData.OutCode);
                taskData.RemoteFileFullPath = string.Concat(taskData.OutPath, taskData.TargetRelativePath.Replace("\\", "/"));
            }
        }

        private string GetRemoteFile(string cid, string fileurl,string fileName)
        {
            try
            {
                string tmpDir = Path.Combine(RuntimeAdapter.AppDir, _runSiteConfig.TempDirectory, DateTime.Now.ToString("yyyyMM/dd").Replace("/", "\\")); 
                if (!Directory.Exists(tmpDir))
                {
                    Directory.CreateDirectory(tmpDir);
                }
                string tmpFileFullPath = Path.Combine(tmpDir, fileName);
                ShowDebugMessageExt(cid, "将开始下载媒体文件[Picture]  {0} {1}", fileurl, tmpFileFullPath);
                if (WebHelper.GetRemoteFile(fileurl, tmpFileFullPath))
                {
                    ShowDebugMessageExt(cid, "媒体文件[Picture] {0}下载成功 ", fileName);
                    return tmpFileFullPath;
                }
                else
                {
                    ShowErrMessageExt(cid, "媒体文件[Picture] {0}下载失败 ", fileName);
                    UpdateRemoteTaskStat(cid, "停止", 0);
                    UpdateTopTaskState(cid, -1);
                    return "";
                }
            }
            catch (Exception ex)
            {
                ShowErrMessageExt(cid, "媒体文件[Picture] {0}下载失败{1} ", fileName, ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// 复制任务执行
        /// </summary>
        private void CopyTaskRun(string correlateId, string remotePath, string localPath)
        {
            try
            {
                UpdateTopTaskState(correlateId, 2);
                using (MediaReplication copier = new MediaReplication(localPath, remotePath))
                {
                    copier.LogOutName = correlateId;
                    copier.WriteConsoleMessageEvent = WriteConsoleMessageEvent;
                    copier.UpdateUploadTaskStat = UploadStatusUpdate;
                    copier.UploadTaskEndEvent = TaskEnd;
                    copier.Run(correlateId);
                }
            }
            catch (Exception ex)
            {
                UpdateRemoteTaskStat(correlateId, "停止", 0, ex.Message);
                UpdateTopTaskState(correlateId, -1);
                WriteErrMessageExt(correlateId, ex.ToString());
            }
        }

        /// <summary>
        /// 上传任务执行
        /// </summary>
        /// <param name="correlateId"></param>
        /// <param name="remoteUrl"></param>
        /// <param name="localAddress"></param>
        private void UploadTaskRun(string correlateId, string remoteUrl, string localAddress)
        {
            try
            {
                string mediaSizeStr = string.Empty;
                long mediaSize = 0;
                FileInfo media = new FileInfo(localAddress);
                if (media != null)
                {
                    mediaSize = media.Length;
                    mediaSizeStr = DataTransfer.FormatLengthStr(mediaSize);
                    ShowDebugMessageExt(correlateId, "本地文件{0}大小为{1}", localAddress, mediaSizeStr);
                }
                UpdateRemoteTaskStat(correlateId, "处理中", 1, string.Format("文件{0}大小为{1}", localAddress, mediaSizeStr));
                UpdateTopTaskName(correlateId, DataTransfer.FormatLengthShortStr(mediaSize));
                UpdateTopTaskState(correlateId, 2);

                using (MediaUploader uploader = new MediaUploader(remoteUrl, localAddress, _runSiteConfig.UploadCache))
                {
                    uploader.LogOutName = correlateId;
                    uploader.WriteConsoleMessageEvent = WriteConsoleMessageEvent;
                    uploader.UpdateUploadTaskStat = UploadStatusUpdate;
                    uploader.UploadTaskEndEvent = TaskEnd;
                    uploader.Run(correlateId);
                };
            }
            catch (Exception ex)
            {
                UpdateRemoteTaskStat(correlateId, "停止", 0, ex.Message);
                UpdateTopTaskState(correlateId, -1);
                WriteErrMessageExt(correlateId, ex.ToString());
            }
        }

        private void UploadStatusUpdate(string correlateId, EnumUploadTaskStatus taskStatus, int percentage)
        {
            switch (taskStatus)
            {
                case EnumUploadTaskStatus.Exec:
                    UpdateTaskStat(correlateId, 1);  //0表示待执行 1表示执行中 2表示执行完成 -1 表示执行失败需重试的，重试满了还是不行直接为2
                    UpdateRemoteTaskStat(correlateId, "处理中", percentage);
                    break;
                case EnumUploadTaskStatus.End:
                    UpdateTaskStat(correlateId, 2);
                    UpdateRemoteTaskStat(correlateId, "完成", 100);
                    break;
                default:
                    UpdateTaskStat(correlateId, -1);
                    UpdateRemoteTaskStat(correlateId, "停止", 0);
                    break;
            }
        }

        private void UpdateTaskStat(string correlateId, int stat)
        {
            try
            {
                if (!string.IsNullOrEmpty(correlateId))
                {
                    if (taskList.ContainsKey(correlateId))
                    {
                        taskList[correlateId] = stat;
                    }
                }
            }
            catch (Exception ex)
            {
                ShowDebugMessage(ex.ToString());
                
            }
            

        }

        private void UpdateRemoteTaskStat(string correlateId, string stat, int percentage, string message = "")
        {
            try
            {
                if (taskModels.Exists(t => t.Id == correlateId))
                {
                    var taskinfo = taskModels.Find(t => t.Id == correlateId);
                    //JsonAssistant.FromFile<TaskReportModel>(reportTemplatefullPath);
                    TaskReportModel reportData = new TaskReportModel()
                    {
                        Id = correlateId,
                        FileName = taskinfo.FileName,
                        OutCode = taskinfo.OutCode,
                        OutName = taskinfo.OutName,
                        Status = stat,
                        Progress = percentage,
                        ErrorCount = string.IsNullOrEmpty(message) ? 0 : 1,
                        ErrorMessage = message,
                        CreationTime = DateTime.Now,
                        FinishTime = percentage == 100 ? DateTime.Now : DateTime.MinValue
                    };

                    string postData = JsonAssistant.Serialize(reportData);
                    ShowDebugMessageExt(correlateId, "开始任务执行状态上报{0}", postData);
                    string responseStr = WebHelper.GetHttpResponse(_statSrvApiUrl, "POST", "application/json", postData);
                    ShowDebugMessageExt(correlateId, "上报信息回执 {0}", responseStr);
                }
            }
            catch (Exception ex)
            {
                ShowErrMessage(correlateId, ex.ToString());
            }

        }

        /// <summary>
        /// 更新页面任务状态
        /// </summary>
        /// <param name="tmpTask"></param>
        /// <param name="stat"></param>
        private void UpdateRemoteTaskStat(TaskModel tmpTask, string stat)
        {
            try
            {
                if (tmpTask != null)
                {
                    TaskReportModel reportData = new TaskReportModel()
                    {
                        Id = tmpTask.Id,
                        FileName = tmpTask.FileName,
                        OutCode = tmpTask.OutCode,
                        OutName = tmpTask.OutName,
                        Status = stat,
                        Progress = 0,
                        OutType = tmpTask.OutType,
                        OutPath = tmpTask.OutPath,
                        CreationTime = DateTime.Now,
                        FinishTime = DateTime.MinValue
                    };

                    string postData = JsonAssistant.Serialize(reportData);
                    ShowDebugMessageExt(tmpTask.Id, "开始任务执行状态上报 {0}", postData);
                    string responseStr = WebHelper.GetHttpResponse(_statSrvApiUrl, "POST", "application/json", postData);
                    ShowDebugMessageExt(tmpTask.Id, "更新回执信息为 {0}", responseStr);
                }
            }
            catch (Exception ex)
            {
                ShowErrMessage(ex.ToString());
            }
        }

        private void TaskEnd(string tid, bool stat, string message = "")
        {
            if (stat)
            {
                //_averageSpeed = (_minSpeed + _maxSpeed) / 2;
                //ShowDebugMessageExt(tid, string.Format("本次上传工作完成，最小速率为{0}，最大速率为{1}，平均速率为{2}", GetFlowSpeed(_minSpeed), GetFlowSpeed(_maxSpeed), GetFlowSpeed(_averageSpeed)));

                EndTopTask(tid, 5);
                UpdateTaskStat(tid, 2);
                UpdateRemoteTaskStat(tid, "完成", 100, message);
            }
            else
            {
                EndTopTask(tid, -1);
                UpdateTaskStat(tid, -1);
                //失败的任务，进度归零
                UpdateRemoteTaskStat(tid, "停止", 0, message);
            }

            ShowDebugMessageExt(tid, "文件上传任务结束 状态为[{0}]", stat);
        }
        
        /// <summary>
        /// 析构函数
        /// </summary>
        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        #region 前端任务处理
        /// <summary>
        /// 更新前端任务列表基础数据
        /// </summary>
        /// <param name="correlateId"></param>
        /// <param name="tag"></param>
        /// <param name="siteName"></param>
        private void UpdateTopTaskInfo(string correlateId, string tag, string siteName)
        {
            try
            {
                //通过任务编号找到缓存中执行的任务数据
                var runTaskItem = RuntimeAdapter.Tasks.Find(t => t.ID == correlateId);
                if (runTaskItem != null)
                {
                    runTaskItem.Comment = correlateId; // itemCfg.FileSets[0].Group;
                    runTaskItem.Tag = tag; // itemCfg.Tag;
                    runTaskItem.Name = siteName; // itemCfg.Site;
                }
            }
            catch (Exception ex)
            {
                ShowDebugMessage(ex.ToString());
            }
            
        }

        private void UpdateTopTaskName(string correlateId, string siteName)
        {
            try
            {
                //通过任务编号找到缓存中执行的任务数据
                var runTaskItem = RuntimeAdapter.Tasks.Find(t => t.ID == correlateId);
                if (runTaskItem != null)
                {
                    runTaskItem.Comment = string.Concat(runTaskItem.Comment, "[",siteName, "]"); // itemCfg.FileSets[0].Group;
                }
            }
            catch (Exception ex)
            {
                ShowDebugMessage(ex.ToString());
            }

        }

        /// <summary>
        /// 更新前端任务状态
        /// </summary>
        /// <param name="tid"></param>
        /// <param name="value"></param>
        private void UpdateTopTaskState(string tid, int value)
        {
            try
            {
                if (RuntimeAdapter.Tasks.Exists(t => t.ID == tid))
                {
                    var runTaskItem = RuntimeAdapter.Tasks.Find(t => t.ID == tid);
                    runTaskItem.State = value;
                }
                else
                {
                    ShowDebugMessageExt(tid, "未找到编号为{0}的任务");
                }
            }
            catch (Exception ex)
            {
                ShowDebugMessage(ex.ToString());
            }
            
            //RuntimeAdapter.Tasks.Find(t => t.ID == TaskID).State = value;
        }
        /// <summary>
        /// 结束任务
        /// </summary>
        /// <param name="tid"></param>
        /// <param name="value"></param>
        private void EndTopTask(string tid, int value)
        {
            //两种方式写前台监控队列的值
            RuntimeAdapter.Tasks.ForEach(delegate (RunTask t) { if (t.ID == tid) { t.State = value; t.EndTime = DateTime.Now; } });
            //RuntimeAdapter.Tasks.Find(t => t.ID == TaskID).State = responseMsg.Code;
            //RuntimeAdapter.Tasks.Find(t => t.ID == TaskID).EndTime = DateTime.Now;
        }
        #endregion 前端任务处理

        #region 日志上报实现
        /// <summary>
        /// 日志上报实现
        /// </summary>
        /// <param name="head">工单流水号</param>
        /// <param name="msg">下载结果</param>
        /// <param name="type">日志类型</param>
        public void PushLog(string head, string msg, EnumLogLevel type)
        {
            try
            {
                if (RuntimeAdapter.AllowReportLog)
                {
                    WriteDebugMessageExt(head, "启动{0}日志上报，内容为：{1}", type.ToString(), msg);
                    ShowDebugMessage("启动{0}日志上报，内容为：{1}", type.ToString(), msg);
                    Loginfo log = new Loginfo() { SamName = RuntimeAdapter.HostName, LogType = type, Head = head, Message = msg };
                    string rtnMsg = WebHelper.GetHttpResponse(RuntimeAdapter.LogEngine, "POST", "application/json", JsonAssistant.Serialize(log));
                }
            }
            catch (Exception ex)
            {
                ShowErrMessage("日志上报异常：{0}", ex.ToString());
            }

        }
        #endregion 日志处理
    }

    /// <summary>
    /// 
    /// </summary>
    public class RunProgress
    {
        /// <summary>
        /// 
        /// </summary>
        public string File { get; set; }
        /// <summary>
        /// 
        /// </summary>
        public int Progress { get; set; }
    }

}
